//*******变量声明************************************************************************
var store;
var productId = -1;
//*******列定义**************************************************************************
var fields = [
	{name: 'pid'},
	{name: 'productCode'},
	{name: 'cusName'},
	{name: 'linker'},
	{name: 'phoneNo'},
	{name: 'productType'},
	{name: 'saleType'},
	{name: 'totalWeight'},
	{name: 'totalPrice'},
	{name: 'outTime'}
];
var baseParams={'product.cusName':'','product.linker':'','product.phoneNo':'','product.saleType':'','product.productCode':''};
var detailsParams={'product.id':''};
if(!Number.prototype.toFixed){ 
	Number.prototype.toFixed = function(n){ 
		with(Math)return round(Number(this)*pow(10,n))/pow(10,n) 
	} 
} 
function dealWithNumber(value){
	return value.toFixed(1);
}
var cm = new Ext.grid.ColumnModel([
    new Ext.grid.RowNumberer(),
    {header: "出货编号",dataIndex: "productCode", width: 120, sortable: true},
    {header: "客户名称",dataIndex: "cusName", width: 100, sortable: true},
    {header: "取货人",dataIndex: "linker",width: 140,sortable: true},
    {header: "联系电话",dataIndex: "phoneNo",width: 140,sortable: true},
    {header: "产品数量",dataIndex: "productType",width: 70,sortable: true},
    {header: "出货类别",dataIndex: "saleType",width: 70,sortable: true},
    {header: "总重量",dataIndex: "totalWeight",width: 100,sortable: true,renderer: dealWithNumber},
    {header: "总金额",dataIndex: "totalPrice",width: 100,sortable: true,renderer: dealWithNumber},
    {header: "出货时间",dataIndex: "outTime",width: 100,sortable: true}
]);
//*******查询条件*************************************************************************
//客户名称
var cusNameT = new Ext.form.TextField({
	width:100,
    allowNegative: false
});
//电话号码
var phoneNoT = new Ext.form.TextField({
	width:100,
    allowNegative: false
});
//出货类别
var saleTypeT = new Ext.form.TextField({
	width:50,
    allowNegative: false
});
//取货人
var linkerT = new Ext.form.TextField({
	width:100,
    allowNegative: false
});
//出货编号
var productCodeT = new Ext.form.TextField({
	width:100,
    allowNegative: false
});
//统计时段
var datestore = new Ext.data.SimpleStore({
    fields: ['value', 'text'],
    data : [['','请选择...'],['month','前个月'],['week', '前一周'],['day','前一天'],['hour', '前个小时'],['bhour', '前半小时']]
});
 var datechange = new Ext.form.ComboBox({
    store: datestore,
    width:70,
    typeAhead: true,
    mode: 'local',
    forceSelection: true,
    triggerAction: 'all',
    emptyText:'请选择...',
    selectOnFocus:true,
	valueField:'value',
	displayField:'text',
	listeners:{
		'select':function(){
	          if(datechange.getValue()!=''){
	          	dateBegin.disable();
	          	dateEnd.disable();
	          }else{
	          	dateBegin.enable();
	          	dateEnd.enable(); 
	          }
  		}
	}
});
// 开始和结束时间
var dt = new Date();
var time = dt.format('Y-m-d')+" 23:59:59";
var dateBegin = new Ext.form.TextField({
    name: 'starttime',
    id: 'starttime',
    width: 100,
    readOnly: true,
    //value:time,
    listeners:{
		'render':function(){
	       Ext.EventManager.on("starttime", 'click', function(){
	           new  WdatePicker({
	                skin: 'ext',                            // 应用ext的皮肤样式
	                dateFmt: 'yyyy-MM-dd HH:mm:ss'                   // 格式为：年-月
	             });
	      })
  		}
	}
});
   var dateEnd = new Ext.form.TextField({
    name: 'endtime',
    id: 'endtime',
    width: 100,
    readOnly: true,
    value:time,
    listeners:{
	   'render':function(){
	       Ext.EventManager.on("endtime", 'click', function(){
	           new  WdatePicker({
	                skin: 'ext',                            // 应用ext的皮肤样式
	                dateFmt: 'yyyy-MM-dd HH:mm:ss'                   // 格式为：年-月
	             });
	      })
   		}
   }
});
// 查询条件Bar
 var tbar = new Ext.Toolbar({
	 scope:this,height:25,items:['出货编号:',productCodeT,'-','客户名称:',cusNameT,'-','取货人:',linkerT,'-','联系电话:',phoneNoT,'-','出货类别:',saleTypeT,
      '-','开始时间:',dateBegin,'-','结束时间:',dateEnd,
      '-',{ 
         text:'查询',
	    	 pressed: true,
			 handler:function()
			 {
				 query();
			 }
	 	},'-',{ 
	        text: '删除',
	        pressed: true,
	        handler:function(){
	        	if(productId != -1)
	        		deleteRecord();
	        	else
	        		Ext.Msg.alert('信息','请先点击表格选择需要删除的记录');
			}
		},'-',{ 
	        text: '导出',
	        pressed: true,
	        handler:function(){
	        	if(productId != -1)
	        		window.open(contextRootPath + '/product/export.do?productId='+productId);
	        	else
	        		Ext.Msg.alert('信息','请先点击表格选择需要导出的记录');
			}
		}]
});
 
function query(){
	// 先验证查询条件
 	var dateType = datechange.getValue();
 	var startTime = dateBegin.getValue();
 	var endTime = dateEnd.getValue();
 	if(dateType == '' 
 		&& (startTime == '' && endTime == '')){
 		Ext.Msg.alert('信息','请先选择时间段或者选择开始时间和结束时间！');
 		return;
 	}
 	// 开始查询
 	store.removeAll();
    store.baseParams['product.cusName']=cusNameT.getValue();
    store.baseParams['product.linker']=linkerT.getValue();
    store.baseParams['product.saleType']=saleTypeT.getValue();
    store.baseParams['product.phoneNo']=phoneNoT.getValue();
    store.baseParams['product.productCode']=productCodeT.getValue();
    store.baseParams['startTime']=startTime;
    store.baseParams['endTime']=endTime;
    store.reload({params:{start:0, limit:25}});
}
 
function deleteRecord(){
	Ext.MessageBox.show({
        msg: '正在删除数据,请稍候...',
        progressText: '删除...',
        width:300,
        wait:true,
        waitConfig: {interval:200},
        icon:'ext-mb-download'
    });
	Ext.Ajax.request({
	   url: contextRootPath+'/product/delete.do',
	   success: function(response,o){
		   	Ext.MessageBox.hide();
		   	if(response.responseText == 'success')
		   		Ext.Msg.alert('信息','删除成功！');
		   	else
		   		Ext.Msg.alert('信息','删除失败！');
		   	query();
	   },
	   failure: function(){
		   Ext.Msg.alert('信息','删除失败！');
	   },
	   params: {'productId':productId}
	});
}

// 初始化页面信息和表格
Ext.onReady(function(){
	/****gridPanel******/
    var grid = new Ext.ux.ReportGridPanel({
        id:'grid',
        region:'center',
        fields:fields,
        baseParams:baseParams,
        url:contextRootPath + '/product/query.do',
        width:700,
        height:500,
        title:'出货记录查询',       
        cm:cm,
        trackMouseOver:false,
        tbar:tbar
    });
    var viewport = new Ext.Viewport({   //视图
           layout:'border',
           items:[grid]
    }); 
  	store = grid.getStore();
    
  	// 查询明细
    grid.on("rowdblclick",function(_grid ,  _rowIndex, e){
	 	/*var _sm=grid.selModel;
	 	var selec_record=_sm.getSelected();
	 	if(selec_record == undefined || selec_record == ''){
	 		Ext.Msg.alert('信息','请先选择记录！');
	 		return;
	 	}
 	 	var tbs = selec_record.get('equip_name');
 	 	var tbsName = selec_record.get('equName');
 	 	var storeDetatil = gridDetail.getStore();
 	 	storeDetatil.removeAll();
		detailwin.show();
		storeDetatil.baseParams.dateBegin=dateBegin.getValue();
		storeDetatil.baseParams.dateEnd=dateEnd.getValue();
		storeDetatil.baseParams.date=datechange.getValue();
	    storeDetatil.baseParams.tbs=tbs;
	    storeDetatil.baseParams.equName=tbsName;
		storeDetatil.load({params:{start:0, limit:25}});*/
	});
    grid.on('rowclick',function(g,rowIndex,e){
    	var record = store.getAt(rowIndex);
    	productId = record.get('pid');
    });

	var colmlDetail=new Ext.grid.ColumnModel([
		{header: "交换机/基站",dataIndex: "equName", width: 100, sortable: true},
		{header: "建立时间",dataIndex: "startTime",width: 140,sortable: true},
		{header: "释放时间",dataIndex: "stopTime",width: 140,sortable: true},
		{header: "位置登记次数（交换机内）",dataIndex: "updateInDxt",width: 160,sortable: true},
		{header: "位置登记次数(交换机间）",dataIndex: "updateViaDxt",width: 160,sortable: true},
		{header: "业务请求数",dataIndex: "businessReqCount",width: 100,sortable: true}
	]);
	var detailField = [
       	{name: 'equip_name'},          
        {name: 'equName'},
    	{name: 'updateInDxt'},
    	{name: 'updateViaDxt'},
    	{name: 'businessReqCount'},
    	{name: 'startTime'},
    	{name: 'stopTime'}
	];
 
    var gridDetail=new Ext.ux.ReportGridPanel({
    	region:'center',
        cm:colmlDetail,
        trackMouseOver:false,
        disableSelection:true,
        fields:detailField,
        baseParams:detailsParams,
        url:contextRootPath + '/locationupdate/getDetails.do'
    });
    
	var detailwin=new Ext.Window({
		title:"位置登记率统计明细",
		bodyStyle:'padding:5px',
		layout : 'border',
		closeAction :'hide',
		plain: true,
		frame: true,
		id:'addwind',
		width: 750,
		height:320,
      	labelWidth:55,
    	items:[gridDetail],
      	showlock:false,
     	buttons:[{ 
	        text: '导出excel',
	        pressed: true,
	        handler:function(){       
	            window.open(contextRootPath + '/locationupdate/exportDetails.do');                    
			}
		},{
        	text:"关闭",
           	handler:function(){
            	detailwin.hide();
        	}
	  	}]
 	});     
});